import axios from "axios";
import { Toast } from "mint-ui";
import qs from "querystring";
// get请求
async function get(url) {
  const token = sessionStorage.getItem("TOKEN") || "";
  try {
    const requestConfig = {
      headers: {
        "X-Auth-Token": token
      }
    };
    const urlStr = `${url}`;
    const response = await axios.get(urlStr, requestConfig);
    if (response.data.statusCode == 10002) {
      Toast({ message: "服务器异常!", position: "bottom" });
      return Promise.reject("Token过期，请重新登录");
    } else {
      return response.data;
    }
  } catch (error) {
    console.log("error", error);
    Toast({ message: "服务器异常!", position: "bottom" });
  } finally {
  }
}
// post请求
async function post(url, param) {
  const token = sessionStorage.getItem("TOKEN") || "";
  try {
    const requestConfig = {
      headers: {
        "Content-Type": "application/json",
        responseType: "json",
        "X-Auth-Token": token
      }
    };

    const urlStr = `${url}`;
    const paramStr = qs.stringify({ ...param });
    const response = await axios.post(
      urlStr,
      JSON.stringify(param),
      requestConfig
    );
    return response.data;
  } catch (error) {
    console.log("error", error);
    Toast({ message: "服务器异常!", position: "bottom" });
  } finally {
  }
}
// postUrlencoded请求
async function postUrlencoded(url, param) {
  const token = sessionStorage.getItem("TOKEN") || "";
  try {
    // application/x-www-form-urlencoded; charset=UTF-8  application/json
    const requestConfig = {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        responseType: "json",
        "X-Auth-Token": token
      }
    };

    const urlStr = `${url}`;
    const paramStr = qs.stringify({ ...param });
    const response = await axios.post(urlStr, paramStr, requestConfig);
    return response.data;
  } catch (error) {
    console.log("error", error);
    Toast({ message: "服务器异常!", position: "bottom" });
  } finally {
  }
}
// formData-post请求
async function formDataType(url, param) {
  const token = sessionStorage.getItem("TOKEN") || "";
  try {
    const requestConfig = {
      headers: {
        "Content-Type": "multipart/form-data",
        responseType: "json",
        token: token
      }
    };

    const urlStr = `${url}`;
    const paramStr = qs.stringify({ ...param });
    const response = await axios.post(urlStr, param, requestConfig);
    return response.data;
  } catch (error) {
    console.log("error", error);
    Toast({ message: "服务器异常!", position: "bottom" });
  } finally {
  }
}

export { get, post, formDataType, postUrlencoded };
